package com.eii.resubmit.aop.request;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author eii
 * @time 2020/11/28 9:36 下午
 */
public class UServlet {

    /**
     * 获取真实地址
     * @param request HttpServletRequest 请求
     */
    public static String getAddr(HttpServletRequest request) {
        String address = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(address) || "unknown".equalsIgnoreCase(address)) {
            address = request.getHeader("Proxy-Client-address");
        } else {
            return address;
        }
        if (StringUtils.isEmpty(address) || "unknown".equalsIgnoreCase(address)) {
            address = request.getHeader("WL-Proxy-Client-address");
        } else {
            return address;
        }
        if (StringUtils.isEmpty(address) || "unknown".equalsIgnoreCase(address)) {
            address = request.getHeader("HTTP_CLIENT_address");
        } else {
            return address;
        }
        if (StringUtils.isEmpty(address) || "unknown".equalsIgnoreCase(address)) {
            address = request.getHeader("HTTP_X_FORWARDED_FOR");
        } else {
            return address;
        }
        if (StringUtils.isEmpty(address) || "unknown".equalsIgnoreCase(address)) {
            address = request.getRemoteAddr();
        } else {
            return address;
        }
        return address;
    }

    /**
     * 从spring上下文中获取HttpServletRequest
     */
    public static HttpServletRequest request() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
}
